from typing import Optional

from com.linkstec.dao.user_dao import UserDao
from com.linkstec.dao.user_history_dao import UserHistoryDao
from com.linkstec.models.user import User
from com.linkstec.models.user_history import UserHistory
from com.linkstec.utils.db_utils import TransactionContext
from datetime import datetime


class UserService:
    def create_user(self, user: User) -> User:
        with TransactionContext() as conn:
            user_repo = UserDao(conn)
            user_id = user_repo.create(user)
            return user_repo.find_by_id(user_id)

    def update_user(self, user: User) -> User:
        with TransactionContext() as conn:
            # 获取原始记录
            user_repo = UserDao(conn)
            original_user = user_repo.find_by_id(user.id)

            # 更新用户
            user_repo.update(user)

            # 记录历史
            history_repo = UserHistoryDao(conn)
            history = UserHistory(
                user_id=user.id,
                action_type="UPDATE",
                old_value=f"{original_user.username}|{original_user.email}",
                new_value=f"{user.username}|{user.email}",
                created_at=datetime.now()
            )
            history_repo.create_history(history)

            return user_repo.find_by_id(user.id)

    def delete_user(self, user_id: int) -> bool:
        with TransactionContext() as conn:
            user_repo = UserDao(conn)
            history_repo = UserHistoryDao(conn)

            # 记录删除操作
            user = user_repo.find_by_id(user_id)
            if user:
                history = UserHistory(
                    user_id=user_id,
                    action_type="DELETE",
                    old_value=f"{user.username}|{user.email}",
                    new_value="",
                    created_at=datetime.now()
                )
                history_repo.create_history(history)

            return user_repo.delete(user_id) > 0

    def get_user(self, user_id: int) -> Optional[User]:
        """获取单个用户"""
        with TransactionContext() as conn:
            return UserDao(conn).find_by_id(user_id)

    def list_users(self) -> list[User]:
        """获取所有用户列表"""
        with TransactionContext() as conn:
            return UserDao(conn).find_all()